<template>
  <el-container style="height: 100vh; border: 1px solid #eee">
    <el-aside width="200px" style="background-color: rgb(238, 241, 246)">
      <el-menu default-active="1-1" class="el-menu-vertical-demo">
        <el-menu-item index="0" @click="handleShowAllReservations" v-if="userIdentity === 'ad'">
          <i class="el-icon-s-order"></i>全部预约
        </el-menu-item>
        <el-submenu index="1" v-if="userIdentity === 'mem'">
          <template slot="title"><i class="el-icon-message"></i>预约</template>
          <el-menu-item index="1-1" @click="handleShowCourses">课程预约</el-menu-item>
          <el-menu-item index="1-2" @click="handleShowCoaches">教练预约</el-menu-item>
        </el-submenu>
        <el-submenu index="2" v-if="userIdentity === 'mem'">
          <template slot="title"><i class="el-icon-date"></i>我的预约</template>
          <el-menu-item index="2-1" @click="handleMyCourses">课程</el-menu-item>
          <el-menu-item index="2-2" @click="handleMyCoaches">教练</el-menu-item>
        </el-submenu>
        <el-menu-item index="3" @click="goCoaches" v-if="userIdentity === 'mem'">
          <i class="el-icon-user"></i>教练一览
        </el-menu-item>
        <el-menu-item index="4" @click="goHome">
          <i class="el-icon-back"></i>返回首页
        </el-menu-item>
      </el-menu>
    </el-aside>
    
    <el-main :style="backgroundStyle">
      <div v-if="showAllReservations">
        <el-button @click="showAllCoachReservations">教练</el-button>
        <el-button @click="showAllCourseReservations">课程</el-button>
      </div>
        <div v-if="showAllCoachReservationsData">
  <el-table :data="allCoachReservations" style="width: 100%">
    <el-table-column prop="coachName" label="教练" width="120"></el-table-column>
    <el-table-column prop="username" label="用户名" width="120"></el-table-column>
    <el-table-column prop="reservationTime" label="课程时间" width="180"></el-table-column>
    <el-table-column label="操作">
      <template slot-scope="scope">
        <el-button type="text" icon="el-icon-delete" @click="deleteCoachReservation(scope.row)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>
  <el-pagination
    @current-change="handlePageChange"
    :current-page="currentPage"
    :page-size="pageSize"
    :total="allCoachReservations.length"
    layout="total, prev, pager, next, jumper">
  </el-pagination>
</div>

<div v-if="showAllCourseReservationsData">
  <el-table :data="allCourseReservations" style="width: 100%">
    <el-table-column prop="courseName" label="课程名称" width="120"></el-table-column>
    <el-table-column prop="coachName" label="教练" width="120"></el-table-column>
    <el-table-column prop="username" label="用户名" width="120"></el-table-column>
    <el-table-column prop="reservationTime" label="课程时间" width="180"></el-table-column>
    <el-table-column label="操作">
      <template slot-scope="scope">
        <el-button type="text" icon="el-icon-delete" @click="deleteCourseReservation(scope.row)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>
  <el-pagination
    @current-change="handlePageChange"
    :current-page="currentPage"
    :page-size="pageSize"
    :total="allCourseReservations.length"
    layout="total, prev, pager, next, jumper">
  </el-pagination>
</div>

      <div v-if="showCourses">
        <el-table :data="courses" style="width: 100%">
          <el-table-column prop="reservationId" label="☆" width="60"></el-table-column>
          <el-table-column prop="name" label="课程名称" width="120"></el-table-column>
          <el-table-column prop="coach" label="教练"></el-table-column>
          <el-table-column prop="date" label="课程时间" width="180"></el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button @click="reserveCourse(scope.row)">预约</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div v-if="showCoachesSection">
        <el-table :data="coaches" style="width: 100%">
          <el-table-column prop="id" label="☆" width="60"></el-table-column>
          <el-table-column prop="name" label="教练"></el-table-column>
          <el-table-column label="时间">
            <template slot-scope="scope">
              <ul>
                <li v-for="(time, index) in scope.row.times" :key="index">
                  {{ time }}
                  <el-button @click="reserveCoach({ coach: scope.row.name, time: time, id: scope.row.id })">预约</el-button>
                </li>
              </ul>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div v-if="showMyCourses">
        <el-table :data="myCoursesData" style="width: 100%">
          <el-table-column prop="reservationId" label="☆" width="80"></el-table-column>
          <el-table-column prop="courseId" label="☆" width="80"></el-table-column>
          <el-table-column prop="courseName" label="课程名称" width="120"></el-table-column>
          <el-table-column prop="coachName" label="教练" width="120"></el-table-column>
          <el-table-column prop="reservationTime" label="课程时间" width="180"></el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button type="text" icon="el-icon-delete" @click="cancelCourseReservation(scope.row)">取消</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div v-if="showMyCoaches">
        <el-table :data="myCoachesData" style="width: 100%">
          <el-table-column prop="reservationId" label="☆" width="80"></el-table-column>
          <el-table-column prop="coachId" label="☆" width="80"></el-table-column>
          <el-table-column prop="coachName" label="教练" width="120"></el-table-column>
          <el-table-column prop="reservationTime" label="时间" width="180"></el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button type="text" icon="el-icon-delete" @click="cancelCoachReservation(scope.row)">取消</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-main>
  </el-container>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      userIdentity: '',
    currentUserName: '',
    showCourses: false,
    showCoachesSection: false,
    showMyCourses: false,
    showMyCoaches: false,
    showAllReservations: false,
    showAllCoachReservationsData: false,
    showAllCourseReservationsData: false,
    allCoachReservations: [], // 确保包含 reservationDate 字段
    allCourseReservations: [], // 确保包含 reservationDate 字段
    currentPage: 1, 
    pageSize: 5, 
      courses: [
        { id: 1, name: '瑜伽', date: '周一 16:30-17:20', coach: 'Sana' },
        { id: 2, name: '健身操', date: '周一 17:30-18:20', coach: 'Lily' },
        { id: 3, name: '现代舞', date: '周一 18:30-19:20', coach: 'Judy' },
        { id: 4, name: '动感单车', date: '周一 19:30-20:20', coach: 'Jake' },
        { id: 5, name: '核心训练', date: '周二 16:30-17:20', coach: 'Joshua' },
        { id: 6, name: '杠铃操', date: '周二 17:30-18:20', coach: 'Felix' },
        { id: 7, name: '普拉提', date: '周二 18:30-19:20', coach: 'Karina' },
        { id: 8, name: '蹦床', date: '周二 19:30-20:20', coach: 'Jackson' },
        { id: 9, name: '经络瑜伽', date: '周三 16:30-17:20', coach: 'Giselle' },
        { id: 10, name: '东方舞', date: '周三 17:30-18:20', coach: 'Ning' },
        { id: 11, name: '踏板操', date: '周三 18:30-19:20', coach: 'Winter' },
        { id: 12, name: '动感单车②', date: '周三 19:30-20:20', coach: 'Jackson' },
        { id: 13, name: '核心训练', date: '周四 16:30-17:20', coach: 'Joshua' },
        { id: 14, name: '尊巴', date: '周四 17:30-18:20', coach: 'Jennie' },
        { id: 15, name: '动感单车③', date: '周四 18:30-19:20', coach: 'Rose' },
        { id: 16, name: '流瑜伽', date: '周四 19:30-20:20', coach: 'Lisa' },
        { id: 17, name: '健身球', date: '周五 16:30-17:20', coach: 'Jennie' },
        { id: 18, name: '瑜伽', date: '周五 17:30-18:20', coach: 'Sana' },
        { id: 19, name: '普拉提', date: '周五 18:30-19:20', coach: 'Karina' },
        { id: 20, name: '杠铃操', date: '周五 19:30-20:20', coach: 'Felix' }
      ],
      coaches: [
        { id: 1, name: 'Sana', times: ['周二 14:00-16:00', '周二 16:30-18:30'] },
        { id: 2, name: 'Lily', times: ['周一 14:00-16:00', '周一 16:30-18:30', '周二 14:00-16:00', '周二 16:30-18:30'] },
        { id: 3, name: 'Judy', times: ['周一 14:00-16:00', '周一 16:30-18:30', '周二 14:00-16:00', '周二 16:30-18:30'] },
        { id: 4, name: 'Jake', times: ['周一 14:00-16:00', '周一 16:30-18:30', '周二 14:00-16:00', '周二 16:30-18:30'] },
        { id: 5, name: 'Joshua', times: ['周二 12:00-14:00', '周二 18:20-20:20', '周四 12:00-14:00', '周四 18:20-20:20'] },
        { id: 6, name: 'Felix', times: ['周二 13:00-15:00', '周二 19:20-21:20', '周五 13:00-15:00', '周五 19:20-21:20'] },
        { id: 7, name: 'Karina', times: ['周二 13:00-15:00', '周二 19:20-21:20', '周五 13:00-15:00', '周五 19:20-21:20'] },
        { id: 8, name: 'Jackson', times: ['周二 14:00-16:00', '周二 16:30-18:30', '周三 14:00-16:00', '周三 16:30-18:30'] },
        { id: 9, name: 'Giselle', times: ['周三 14:00-16:00', '周三 16:30-18:30', '周四 14:00-16:00', '周四 16:30-18:30'] },
        { id: 10, name: 'Ning', times: ['周三 14:00-16:00', '周三 16:30-18:30', '周四 14:00-16:00', '周四 16:30-18:30'] },
        { id: 11, name: 'Winter', times: ['周三 14:00-16:00', '周三 16:30-18:30', '周四 14:00-16:00', '周四 16:30-18:30'] },
        { id: 12, name: 'Rose', times: ['周四 14:00-16:00', '周四 16:30-18:30', '周五 14:00-16:00', '周五 16:30-18:30'] },
        { id: 13, name: 'Jennie', times: ['周四 13:00-15:00', '周四 19:20-21:20', '周五 14:00-16:00', '周五 16:30-18:30'] },
        { id: 14, name: 'Lisa', times: ['周四 14:00-16:00', '周四 16:30-18:30', '周五 14:00-16:00', '周五 16:30-18:30'] }
      ],
      myCoursesData: [], // 我的课程预约数据
      myCoachesData: [], // 我的教练预约数据
    };
  },
   computed: {
    backgroundStyle() {
      return {
        'background-image': `url(${require('@/assets/img/preorder.jpg')})`,
        'background-size': 'cover',
        'background-position': 'center'
      };
    }
  },
  methods: {
    calculateReservationDate(selectedTime) {
    const daysOfWeek = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
    const today = new Date();
    const todayDayOfWeek = today.getDay(); // 当前是周几（0: 周日, 1: 周一, ..., 6: 周六）
    const selectedDayOfWeek = daysOfWeek.indexOf(selectedTime.split(' ')[0]); // 用户选择的周几

    // 计算天数差
    let daysDifference = selectedDayOfWeek - todayDayOfWeek;
    if (daysDifference <= 0) {
      daysDifference += 7; // 如果选择的天数小于或等于今天，则加上7天
    }

    // 计算具体的预约日期
    const reservationDate = new Date(today.getTime() + daysDifference * 24 * 60 * 60 * 1000);
    return reservationDate.toISOString().slice(0, 10); // 返回格式为 YYYY-MM-DD
  },
   handleShowAllReservations() {
    this.showAllReservations = true;
    this.showCourses = false;
    this.showCoachesSection = false;
    this.showMyCourses = false;
    this.showMyCoaches = false;
    this.currentPage = 1;
  },
  showAllCoachReservations() {
    this.showAllCoachReservationsData = true;
    this.showAllCourseReservationsData = false;
    this.fetchAllCoachReservations();
  },
  showAllCourseReservations() {
    this.showAllCoachReservationsData = false;
    this.showAllCourseReservationsData = true;
    this.fetchAllCourseReservations();
  },
    fetchAllCoachReservations() {
      axios.get('/api/reservation/all-coach-reservations')
        .then(response => {
          this.allCoachReservations = response.data;
        })
        .catch(error => {
          console.error('获取教练预约信息失败:', error);
        });
    },
    fetchAllCourseReservations() {
      axios.get('/api/reservation/all-course-reservations')
        .then(response => {
          this.allCourseReservations = response.data;
        })
        .catch(error => {
          console.error('获取课程预约信息失败:', error);
        });
    },
    handlePageChange(page) {
      this.currentPage = page; // 更新当前页码
    },
handleShowCourses() {
  this.showCourses = true;
  this.showCoachesSection = false;
  this.showMyCourses = false;
  this.showMyCoaches = false;
},
handleShowCoaches() {
  this.showCourses = false;
  this.showCoachesSection = true;
  this.showMyCourses = false;
  this.showMyCoaches = false;
},
handleMyCourses() {
  this.showCourses = false;
  this.showCoachesSection = false;
  this.showMyCourses = true;
  this.showMyCoaches = false;
  this.fetchMyCourses();
},
handleMyCoaches() {
  this.showCourses = false;
  this.showCoachesSection = false;
  this.showMyCourses = false;
  this.showMyCoaches = true;
  this.fetchMyCoaches();
},
goCoaches() {
  this.$router.push('/coachesView');
},
goHome() {
  this.$router.push('/home');
},
fetchMyCourses() {
  const username = localStorage.getItem('currentUserName'); // 从 localStorage 获取当前登录的用户名
  axios.get(`/api/reservation/course/${username}`)
    .then(response => {
      this.myCoursesData = response.data;
    })
    .catch(error => {
      console.error('获取课程预约信息失败:', error);
    });
},
fetchMyCoaches() {
  const username = localStorage.getItem('currentUserName');
  axios.get(`/api/reservation/coach/${username}`)
    .then(response => {
      this.myCoachesData = response.data;
    })
    .catch(error => {
      console.error('获取教练预约信息失败:', error);
    });
},
reserveCourse(course) {
  const reservation = {
    courseId: course.id,
    courseName: course.name,
    coachName: course.coach,
    username: this.currentUserName, 
    reservationTime: course.date,
    reservationDate: this.calculateReservationDate(course.date), // 计算预约日期
  };
  
  axios.post('/api/reservation/reserve-course', reservation)
    .then(response => {
      if (response.data === "您已预约过啦") {
        this.$message.warning('您已预约过啦');
      } else if (response.data === "预约成功") {
        this.$message.success('课程预约成功');
        this.fetchMyCourses(); 
      } else {
        this.$message.error('课程预约失败');
      }
    })
    .catch(error => {
      console.error('课程预约失败:', error);
      this.$message.error('课程预约失败');
    });
},
reserveCoach(coach) {
  const reservation = {
    coachId: coach.id,
    coachName: coach.coach,
    username: this.currentUserName,
    reservationTime: coach.time,
    reservationDate: this.calculateReservationDate(coach.time), // 计算预约日期
  };
  
  axios.post('/api/reservation/reserve-coach', reservation)
    .then(response => {
      if (response.data === "您已预约过啦") {
        this.$message.warning('您已预约过啦');
      } else if (response.data === "预约成功") {
        this.$message.success('教练预约成功');
        this.fetchMyCoaches(); 
      } else {
        this.$message.error('教练预约失败');
      }
    })
    .catch(error => {
      console.error('教练预约失败:', error);
      this.$message.error('教练预约失败');
    });
},
cancelCourseReservation(reservation) {
  axios.delete(`/api/reservation/delete-course-reservation`, {
    params: {
      courseName: reservation.courseName,
      reservationTime: reservation.reservationTime
    }
  })
  .then(response => {
    this.$message.success('取消课程预约成功');
    this.fetchMyCourses(); // 重新获取我的课程预约信息
  })
  .catch(error => {
    console.error('取消课程预约失败:', error);
    this.$message.error('取消课程预约失败');
  });
},
cancelCoachReservation(reservation) {
  axios.delete(`/api/reservation/delete-coach-reservation`, {
    params: {
      coachName: reservation.coachName,
      reservationTime: reservation.reservationTime
    }
  })
  .then(response => {
    this.$message.success('取消教练预约成功');
    this.fetchMyCoaches(); // 重新获取我的教练预约信息
  })
  .catch(error => {
    console.error('取消教练预约失败:', error);
    this.$message.error('取消教练预约失败');
  });
},
deleteCourseReservation(reservation) {
  axios.delete(`/api/reservation/delete-course-reservation`, {
    params: {
      courseName: reservation.courseName,
      reservationTime: reservation.reservationTime
    }
  })
  .then(response => {
    this.$message.success('取消课程预约成功');
    this.fetchAllCourseReservations(); // 重新获取我的课程预约信息
  })
  .catch(error => {
    console.error('取消课程预约失败:', error);
    this.$message.error('取消课程预约失败');
  });
},
deleteCoachReservation(reservation) {
  axios.delete(`/api/reservation/delete-coach-reservation`, {
    params: {
      coachName: reservation.coachName,
      reservationTime: reservation.reservationTime
    }
  })
  .then(response => {
    this.$message.success('取消教练预约成功');
    // 手动更新本地数据
    this.allCoachReservations = this.allCoachReservations.filter(item =>
      item.coachName !== reservation.coachName || item.reservationTime !== reservation.reservationTime
    );
    // 可选：重新获取数据
    this.fetchAllCoachReservations();
  })
  .catch(error => {
    console.error('取消教练预约失败:', error);
    this.$message.error('取消教练预约失败');
  });
}
},
created() {
this.userIdentity = localStorage.getItem('userIdentity'); // 假设从 localStorage 获取用户身份
this.currentUserName = localStorage.getItem('currentUserName'); // 从 localStorage 获取当前登录的用户名
},
};
</script>
